package com.talkyun.openx.interceptor;

import com.talkyun.openx.interceptor.repeat.RepeatManager;
import com.talkyun.openx.server.core.AbstractInterceptor;
import com.talkyun.openx.server.core.ServiceRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AntiRepeatRequestInterceptor extends AbstractInterceptor {
    private class RepeatRequestException extends RuntimeException {
        private ServiceRequest sr;

        RepeatRequestException(ServiceRequest sr) {
            this.sr = sr;
        }

        @Override
        public String toString() {
            String msg = "Repeat request " + sr.getMapping() + "/" + sr.getMethod() + ":" + sr.getArgs().size();
            // {code:'000610',class:'RepeatRequestException',message:'xxx'}
            return "{\"code\":\"000610\",\"class\":\"" + this.getClass().getName() + "\",\"message\":\"" + msg + "\"}";
        }
    }

    private final Logger logger = LoggerFactory.getLogger(AntiRepeatRequestInterceptor.class);
    private RepeatManager repeatManager = new RepeatManager(500);

    public void setInterval(int ms) {
        repeatManager.updateInterval(ms);
    }

    @Override
    public void doMessageIn(ServiceRequest sr) {
        if (repeatManager.isRepeat(sr)) {
            logger.warn("Repeat request! {}", sr.getMapping() + "/" + sr.getMethod());
            throw new RepeatRequestException(sr);
        }
    }
}